/*
 * @Description: 创建描述节点弹窗
 * @Author: Rfan
 * @Date: 2022-06-28 20:35:00
 * @LastEditTime: 2022-07-06 17:07:38
 */

import { FC, useEffect } from 'react';
import { Button, Form, Modal } from 'antd';
import { ICommonDialog } from '@/interfaces/global';
import { IFolderTreeNode } from '@/interfaces/folderTree';
import { addTreeNodeDesc, ITreeNodeDescParams } from '@/api/floderTree';
import { useFolderTreeContext } from '../../contexts/FolderTreeContext';
import { addTreeNodeById } from '@/utils';
import DescForm from './common/DescForm';

interface CreateDescNodeDialogProps extends ICommonDialog {
  node: IFolderTreeNode | null;
}

const CreateDescNodeDialog: FC<CreateDescNodeDialogProps> = (props) => {
  const { visible, node, onClose } = props;
  const { treeData, expandedKeys, setTreeData, setExpandedKeys } = useFolderTreeContext();
  const [form] = Form.useForm();

  useEffect(() => {
    if (visible) {
      //
    }
  }, [visible]);

  /**
   * @description: 关闭弹窗方法
   */
  const onCancel = () => {
    onClose();
  };

  /**
   * @description: 提交表单方法
   * @param {{ nodeName: string; remark: string }} vals 表单数据
   */
  const onFinish = (vals: { name: string; remark: string }) => {
    if (node && node.id) {
      const params: ITreeNodeDescParams = {
        nodeName: vals.name,
        remark: vals.remark,
        nodeId: node.id
      };
      addTreeNodeDesc(params).then((res) => {
        const { data } = res;
        data.leafNode = true;
        data.isLeaf = true;
        setTreeData(addTreeNodeById(treeData, data.pid, [data]));
        setExpandedKeys([...expandedKeys, data.pid]);
        onClose();
      });
    }
  };

  return (
    <Modal
      title="添加描述节点"
      visible={visible}
      width={400}
      destroyOnClose
      onCancel={onCancel}
      footer={[
        <Button key="close" onClick={onCancel}>
          关闭
        </Button>,
        <Button
          key="save"
          type="primary"
          onClick={() => {
            form.submit();
          }}
        >
          保存
        </Button>
      ]}
    >
      <Form
        form={form}
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 18 }}
        preserve={false}
        onFinish={onFinish}
      >
        <DescForm />
      </Form>
    </Modal>
  );
};

export default CreateDescNodeDialog;
